package com.sunday.aomicaichang.ui.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sunday.common.base.BaseActivity;
import com.sunday.common.event.EventBus;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.aomicaichang.R;
import com.sunday.aomicaichang.http.ApiClient;
import com.sunday.aomicaichang.ui.common.WebViewActivity;
import com.sunday.member.entity.Member;
import com.sunday.member.utils.SignUtil;

import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by yun_sheng on 2017/5/31.
 */

public class RegisterOneActivity extends BaseActivity {
    @Bind(R.id.img_logo)
    ImageView imgLogo;
    @Bind(R.id.edt_phone)
    EditText edtPhone;
    @Bind(R.id.imageView)
    ImageView imageView;
    @Bind(R.id.edt_code)
    EditText edtCode;
    @Bind(R.id.btn_code)
    TextView btnCode;
    @Bind(R.id.ly_register)
    RelativeLayout lyRegister;
    @Bind(R.id.checkbox)
    CheckBox checkbox;
    @Bind(R.id.btn_next)
    TextView btnNext;

    private final static String TAG = "RegisterOneActivity";
    @Bind(R.id.btn)
    TextView btn;
    private Context mContext;
    private static final int LOCK_SECS = 60;
    private StaticHandler mHander = null;
    private int lockCount = 0;
    private Timer mTimer = null;
    private TimerTask mTimeTask = null;
    private static final int UPDATE_COUNT_STATUS = 0;
    private boolean isInputPhoneFomat = false;
    private boolean isInputCodeFomat = false;
    //    private String unionId;
    private String token;
    private boolean check=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register1);
        ButterKnife.bind(this);
        mContext = this;
        mHander = new StaticHandler(this);
        addTextChangedListener();
        checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                check=isChecked;
            }
        });
    }

    @OnClick({R.id.btn_code, R.id.btn_next,R.id.btn})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_code:
                sendCode();
                break;
            case R.id.btn_next:
                register();
                break;
            case R.id.btn:
                String url=ApiClient.API_URL1+"sunday/mobile/advertisement/html5ByZoneCode?zoneKey=member_protocol";
                Intent intent=new Intent(mContext,WebViewActivity.class);
                intent.putExtra("title","用户协议");
                intent.putExtra("url",url);
                startActivity(intent);
                break;
        }
    }

    private void addTextChangedListener() {
        edtPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (edtPhone.getText().toString().length() > 11) {
                    ToastUtils.showToast(mContext, "手机号码最多11位");
                    int i = editable.toString().length() - 1;
                    editable.delete(i, i + 1);
                }
                if (edtPhone.getText().toString().length() == 11)
                    isInputPhoneFomat = true;
                else
                    isInputPhoneFomat = false;

                checkInputState();
            }
        });

        edtCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (edtCode.getText().toString().length() > 6) {
                    ToastUtils.showToast(mContext, "验证码最多4位");
                    int i = editable.toString().length() - 1;
                    editable.delete(i, i + 1);
                }
                if (edtCode.getText().toString().length() == 4)
                    isInputCodeFomat = true;
                else
                    isInputCodeFomat = false;

                checkInputState();
            }
        });
    }

    private void checkInputState() {
//        if (isInputPhoneFomat && isInputCodeFomat)
//            btnNext.setEnabled(true);
//        else
//            btnNext.setEnabled(false);
    }

    private void sendCode() {
        if (edtPhone.getText().toString().length() < 11) {
            ToastUtils.showToast(mContext, "请输入11位手机号码");
            return;
        }
        String nonce = MD5Utils.random();
        String[] str1 = new String[]{"mobile", "type", "nonce"};
        String[] str2 = new String[]{edtPhone.getText().toString(), "2", nonce};
        showLoadingDialog(0);
        Call<ResultDO> call = ApiClient.getApiAdapter().send(edtPhone.getText().toString(), 2,
                nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                dissMissDialog();
                if (isFinish || response.body() == null) {
                    return;
                }
                ResultDO resultDO = response.body();
                if (resultDO.getCode() == 0) {
                    startCountdown(UPDATE_COUNT_STATUS);
                } else {
                    ToastUtils.showToast(mContext, resultDO.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }


    private void register() {
        if(TextUtils.isEmpty(edtPhone.getText().toString())){
            ToastUtils.showToast(mContext,"请输入手机号");
            return;
        }
        if(TextUtils.isEmpty(edtCode.getText().toString())){
            ToastUtils.showToast(mContext,"请输入验证码");
            return;
        }
        if(!check){
            ToastUtils.showToast(mContext,"请同意协议");
            return;
        }
        Call<ResultDO> call = ApiClient.getApiAdapter().check(edtPhone.getText().toString(), 2,
                edtCode.getText().toString());
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                dissMissDialog();
                if (isFinish || response.body() == null) {
                    return;
                }
                ResultDO<Member> resultDO = response.body();
                if (resultDO.getCode() == 0) {
                    Intent intent = new Intent(mContext, RegisterTwoActivity.class);
                    intent.putExtra("code", edtCode.getText().toString());
                    intent.putExtra("phone", edtPhone.getText().toString());
                    startActivity(intent);
                } else {
                    ToastUtils.showToast(mContext, resultDO.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    private static class StaticHandler extends Handler {
        WeakReference<RegisterOneActivity> mActivity;

        StaticHandler(RegisterOneActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            RegisterOneActivity activity = mActivity.get();
            if (null == activity)
                return;

            if (msg.what == UPDATE_COUNT_STATUS) {
                activity.updateUICount();
                //
                if (activity.lockCount == LOCK_SECS) {
                    activity.stopCountdown(UPDATE_COUNT_STATUS);
                }
                activity.lockCount++;
            }
        }
    }

    private void startCountdown(final int id) {

        btnCode.setEnabled(false);
        if (mTimer == null)
            mTimer = new Timer();

        if (null != mTimeTask) {
            mTimeTask.cancel();
            mTimeTask = null;
        }

        if (mTimeTask == null) {
            mTimeTask = new TimerTask() {
                @Override
                public void run() {
                    sendUpdateUIMessage(id);
                }
            };
        }
        mTimer.schedule(mTimeTask, 0, 1000);

    }

    private void sendUpdateUIMessage(int id) {
        if (mHander != null) {
            Message message = Message.obtain(mHander, id);
            mHander.sendMessage(message);
        }
    }

    public void stopCountdown(int id) {
        if (null != mTimer) {
            mTimer.cancel();
            lockCount = 0;
            mTimer = null;
            mTimeTask = null;
        }
        btnCode.setEnabled(true);
        btnCode.setText("获取验证码");
    }

    private void updateUICount() {
        String str = "" + String.valueOf(LOCK_SECS - lockCount) + "";
        btnCode.setText(str + "s");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (null != mTimeTask) {
            mTimeTask.cancel();
            mTimeTask = null;
        }
        if (null != mTimer) {
            mTimer.cancel();
            mTimer = null;
        }
    }
}

